package com.example.bookdemo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import com.example.bookdemo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    private final long VALID_TIME = 60*1000;
    @Autowired
    private CaptchaProperties captchaProperties;
    @RequestMapping("/set")
    public void setCaptcha(HttpServletResponse response){
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(captchaProperties.getHeight(), captchaProperties.getWeight());
        String captchaTxt = captcha.getCode();//获取验证码文本
        System.out.println(captchaTxt);
        captchaProperties.setCode(captchaTxt);
        captchaProperties.setDate(System.currentTimeMillis()+VALID_TIME);
        try {
            response.setHeader("Pragma","No-cache");
            response.setContentType("image/jpeg");
            captcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/get")
    public boolean getCaptcha(String inputCaptcha){
        Assert.hasLength(inputCaptcha,"输入验证码为空");
        if (captchaProperties.getCode().equals(inputCaptcha)&&
        System.currentTimeMillis()<captchaProperties.getDate()){
            return true;
        }
        return false;
    }
}
